/*
 * @Author: ZhaoDong
 * @Date: 2022-07-09 19:39:31
 * @LastEditors: ZhaoDong
 * @LastEditTime: 2022-07-12 10:43:20
 * @Description: UserStore
 */
import store from '/@/store';
import { defineStore } from 'pinia';
import { removeToken, setToken } from '/@/utils/cookies';
import { login, getUserInfo } from '/@/api/modules/login';

const V3_APP_USER = 'V3_APP_USER';
const V3_APP_PERMISSIONS = 'V3_APP_PERMISSIONS';
const V3_APP_TOKEN = 'V3_APP_TOKEN';

export interface IPermission {
  [propName: string]: boolean;
}

export interface IUser {
  name?: string;
  number?: number;
  [propName: string]: any;
}
export interface IUserState {
  token: string;
  permissions: IPermission;
  user: IUser;
}

const getLocalData = <T>(key: string, defaultVal: T): T => {
  try {
    const temp = localStorage.getItem(key);
    if (temp) {
      const localData = JSON.parse(temp);
      return localData ? localData : defaultVal;
    }
    return defaultVal;
  } catch (e) {
    return defaultVal;
  }
};

const permissions = getLocalData(V3_APP_PERMISSIONS, {});
const user = getLocalData<IUser>(V3_APP_USER, {});
const token = getLocalData(V3_APP_TOKEN, '');

export const useUserStore = defineStore({
  id: 'user',
  state: (): IUserState => {
    return {
      token: token,
      permissions: permissions,
      user: user
    };
  },
  getters: {
    isAdmin: (state: IUserState) => {
      return !!state.permissions['*'];
    }
  },
  actions: {
    /** 登录 */
    async login(code: string) {
      const { data } = await login(code);
      const { token, user, permissions }: IUserState = data;
      setToken(token);
      this.token = token;
      this.permissions = permissions;
      this.user = user;
      localStorage.setItem('V3_APP_USER', JSON.stringify(user));
      localStorage.setItem('V3_APP_PERMISSIONS', JSON.stringify(permissions));
      localStorage.setItem('V3_APP_TOKEN', token);
      return Promise.resolve(data);
    },
    /** 获取用户详情 */
    getInfo() {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then((res: any) => {
            resolve(res);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 登出 */
    logout() {
      removeToken();
      this.token = '';
      localStorage.clear();
    },
    /** 重置 Token */
    resetToken() {
      removeToken();
      this.token = '';
      localStorage.clear();
    }
  }
});

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store);
}
